package com.yx.shop.web.filter;

import com.yx.shop.common.Const;
import com.yx.shop.entitly.User;
import com.yx.shop.service.UserService;
import com.yx.shop.service.impl.UserServiceImpl;
import com.yx.shop.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname ${NAME}
 * @Description TODO:
 * @Date 2021/05/06 23:25
 * @Created by yx
 */
@WebFilter(filterName = "AutoFilter", value = "/login.jsp")
public class AutoFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            //本地存在cookie,清空
            String content = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Const.AUTO_NAME)) {
                    content = cookie.getValue();
                }
            }

            if (content != null) {
                //读取存储的账号密码
                content = Base64Utils.decode(content);
                //默认username不含:等特俗字符
                String[] split = content.split(":");
                String username = split[0];
                String password = split[1];
                UserService userService = new UserServiceImpl();
                try {
                    User user = userService.login(username, password);
                    if (user != null) {
                        //用户不为空,可以自动登录
                        request.getSession().setAttribute("loginUser", user);
                        response.sendRedirect("/index.jsp");
                    } else {
                        //自动登录失败,放行
                        chain.doFilter(req, resp);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ServletException e) {
                    e.printStackTrace();
                }

            } else {
                //未设置自动登录,放行
                chain.doFilter(req, resp);
            }
        } else {
            //没有cookie,放行,让用户可以登录
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
